package com.robert.web.mypro.util;

import org.apache.catalina.LifecycleException;
import org.apache.catalina.startup.Tomcat;
import org.apache.log4j.Logger;

import java.io.File;

/**
 * Created by zhenghao on 2016/6/17.
 * tomcat 控制器类
 */
public class EmbededTomcat {


    private final Logger log= Logger.getLogger(this.getClass());

    private Tomcat tomcat=new Tomcat();

    //tomcat 监听端口
    private int port;


    public EmbededTomcat(int port){
        this.port=port;
    }
    public void start()throws Exception{

        //设置端口
        tomcat.setPort(port);

        try{

            //设置项目访问路径
            String contextPath ="";

            //设置项目文件路径
            String docBase =new File("").getAbsolutePath() +"/target/mypro";

            tomcat.addWebapp(contextPath,docBase);

            //启动tomcat
            tomcat.start();

            log.info("Tomcat started.");

            //监听关闭端口，阻塞式。没有这一句，方法执行完后会直接结束
            tomcat.getServer().await();

        }catch( LifecycleException e){
            e.printStackTrace();
            log.error(e.getMessage());
            throw e;
        }

    }

    public void stop()throws Exception{

        tomcat.stop();

        log.info("Tomcat shutdown");
    }



    public static void main(String[] args) throws Exception{

        EmbededTomcat tomcat = new EmbededTomcat(9000);

        //开启线程测试关闭tomcat
        new Shutdown(tomcat).start();

        tomcat.start();

    }


     public static class Shutdown extends Thread {

        private EmbededTomcat tomcat;

        public Shutdown(EmbededTomcat tomcat){

            this.tomcat = tomcat;
        }

        @Override
        public void run() {

            System.out.println("shutdown is running");

            try {
                Thread.sleep(15*1000);      //15秒后执行
                tomcat.stop();
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }
}
